/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.security.shiro.filter;

import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 一个简单的强制登出过滤器
 * 监视 session 中的 {@link #FORCE_LOGOUT_SESSION_KEY}属性, 如果该属性值不为 null 则 logout
 *
 * @author vacoor
 */
public class ForceLogoutFilter extends AccessControlFilter {
    public static final String FORCE_LOGOUT_SESSION_KEY = ForceLogoutFilter.class.getName() + "_SESSION_FORCE_LOGOUT";

    private String forceLogoutUrl;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Session session = getSubject(request, response).getSession(false);
        if (session == null) {
            return true;    // execute next filter
        }
        return session.getAttribute(FORCE_LOGOUT_SESSION_KEY) == null;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        subject.logout();
        saveRequest(request);

        String redirectUrl = StringUtils.hasText(forceLogoutUrl) ? forceLogoutUrl : getLoginUrl();
        WebUtils.issueRedirect(request, response, redirectUrl);
        return false;
    }

    public String getForceLogoutUrl() {
        return forceLogoutUrl;
    }

    public void setForceLogoutUrl(String forceLogoutUrl) {
        this.forceLogoutUrl = forceLogoutUrl;
    }
}
